package com.yuandian.bpm.bi.modules.email.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.yuandian.bpm.bi.modules.email.service.WebHookService;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class WebHookServiceImpl implements WebHookService {


	/**
	 * 向第三方接口发送消息
	 * @param webHookUrl
	 * @param content
	 * @return
	 */
	@Override
	public boolean sendMessage(String webHookUrl, String content) {
		if (ObjectUtil.isEmpty(webHookUrl)) {
			return true;
		}
		try {
			HttpClient httpclient = HttpClients.createDefault();
			HttpPost httppost = new HttpPost(webHookUrl);
			httppost.addHeader("Content-Type", "application/json; charset=utf-8");
			//构建一个json格式字符串textMsg，其内容是接收方需要的参数和消息内容
			StringEntity se = new StringEntity(content, "utf-8");
			httppost.setEntity(se);
			HttpResponse response = httpclient.execute(httppost);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				return true;
			}
		} catch (ClientProtocolException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		return true;
	}
}
